<template>
  <div class="login">
    <div class="login-nav">
      <img src="../assets/logo2.png" alt="" class="top-logo" />
      <el-form :model="ruleForm" ref="ruleFormRef" :rules="rules">
        <el-form-item label="账号" prop="username">
          <el-input v-model="ruleForm.username" prefix-icon="UserFilled" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" prefix-icon="Lock" show-password />
        </el-form-item>
        <el-form-item class="button-nav">
          <el-button type="primary" @click="onSubmit(ruleFormRef)">登录</el-button>
          <el-button type="info" @click="ruleFormRef.resetFields()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { postLoginRequest } from "api/login";

import { onUnmounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
const router = useRouter();
const route = useRoute();
const store = useStore();
postLoginRequest();
let ruleFormRef = ref(null);
let timeIndex;
let ruleForm = reactive({
  username: "",
  password: "",
});
let rules = {
  username: [
    {
      required: true,
      message: "请输入账号",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      min: 6,
      max: 16,
      message: "长度为6到16位",
      trigger: "blur",
    },
  ],
};
const loginError = () => {
  ElMessage.error("登录失败，密码或账号错误");
};
const loginSuccess = () => {
  ElMessage.success("登录成功，Enjoy working");
  timeIndex = setTimeout(() => {
    store.commit("setToken", '');
  }, 30 * 60 * 1000);
};
const onSubmit = (ruleFormRef) => {
  ruleFormRef.validate(async (isValid) => {
    if (isValid) {
      let res = await postLoginRequest(ruleForm);
      if (res.meta.status == 200) {
        store.commit("setToken", res.data.token);
        store.commit("saveUserInfo", ruleForm);
        loginSuccess();
        router.push({
          name: route.query.toName || "home",
        });
      } else {
        loginError();
        ruleFormRef.resetFields();
      }
    }
  });
};
onUnmounted(() => {
  clearTimeout(timeIndex);
})
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  background-color: #2b4b6b;
}

.login-nav {
  border-radius: 20px;
  padding: 60px;
  background-color: white;
  margin: auto;
  width: 300px;
  height: 150px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;

  ::v-deep .el-form-item__content {
    justify-content: center;
  }

  .button-nav {
    margin-top: 40px;
  }

  .top-logo {
    position: absolute;
    top: -60px;
    left: 160px;
    width: 100px;
    height: 100px;
    background-color: aliceblue;
    border-radius: 50%;
    z-index: 10;
    border: 5px solid white;
    box-shadow: 0 0 10px white;
  }
}
</style>
